<template>
	<div style="display: inline-block;max-width: 450px">
		<i class="el-icon-loading" v-show="loading&&!agin"></i>
		<el-button
				v-if="agin"
				:icon="icon"
				@click="load">住院天数自动计算</el-button>
		<span v-if="message">{{ message }}</span>
	</div>
</template>
<script>
	import Vue from 'vue';
	import ElementUI from 'element-ui';
	import AdmissionModel from '../js/config/admission';
	import Service from 'winged/utils/wt-model-service';
	import FormUtils from 'winged/utils/wt-form-utils';
	import ModelUtils from 'winged/utils/wt-model-utils';
	import TimeUtils from 'winged/utils/wt-time-utils';
	import moment from 'moment';
	Vue.use(ElementUI);
	export default {
		name: 'wt-case-discharge-days',
		props: {
			// 字段对象（包含字段配置信息）
			field: {
				type: Object,
				required: true,
			},
			// 表单数据对象
			form: {
				type: Object,
				required: true,
			},
			paramsData: {
				type: Object,
				default: null
			}
		},
		computed: {
			icon() {
				return this.loading ? 'loading' : 'date';
			}
		},
		data() {
			return {
				message: null,
				loading: false,
				agin: false
			};
		},
		methods:{
			reset(){
				this.load();
			},
			load() {
				this.loading = true;
				let _this = this;
				Service.query(AdmissionModel, this.paramsData, function(data) {
					_this.loading = false;
					_this.setQueryResult(FormUtils.parseArray(data));
					_this.agin = false;
				}, function(error) {
					_this.loading = false;
					console.error(error);
					_this.agin = true;
				});
			},
			setQueryResult(data) {
				let admissionDate = null;
				let admissionRecord = null;
				if (data.length == 0){
				}else {
				ModelUtils.normalizeData(AdmissionModel, data[0]);
				let date = data[0].admissionDate;
				date = TimeUtils.format(date,'date');
				let discharge = TimeUtils.format(this.form.dischargeDate,'date');
				if(typeof(discharge) == 'string'){
					discharge = new Date(Date.parse(discharge.replace(/-/g,  "/")));
				}
				if (typeof(date) == 'string'){
					date = new Date(Date.parse(date.replace(/-/g,  "/")));
				}
				if ((admissionDate == null || admissionDate < date) && date <= this.form.dischargeDate) {
					admissionDate = date;
					admissionRecord = data[0];
				}
				}
				if (admissionRecord) {
					let admissionTime = moment(admissionDate);
					let dischargeDate = moment(this.form.dischargeDate).endOf('day');
					let days = dischargeDate.diff(admissionTime, 'days',true);
					days = Math.ceil(days);
					if (days> 1){
						days = days-1
					}
					this.form.hospitalDay = days > 0 ? days : 0;
					this.message = '';
				}
				else {
					this.form.hospitalDay = '';
				}
			}

		},
	}
</script>
